#!/bin/sh

ZIP="$1"
DIR="$2"
REPO_DIR="file://.*/svn.repo"
D="$(dirname "$0")"
D="$(cd "${D}"; pwd)"
BN="$(basename "$0")"
TMPDIR="${D}/tmp.$$~"

cleanUp () {
  rm -rf "${TMPDIR}"
}

trap cleanUp 0 1 2 3 4 5 6 7 8 9 10 12 13 14 15

if [ -z "${ZIP}" ]; then
  echo >&2 "${BN}: Name of the zip file missing"
  exit 1
fi

if [ -z "${DIR}" ]; then
  DIR="$(basename "${ZIP}" .zip)"
fi

if [ ! -s "${ZIP}" ]; then
  echo >&2 "${BN}: File '${ZIP}' not found"
  exit 1
fi

if [ -d "${DIR}" ]; then
  echo >&2 "${BN}: Directory '${DIR}' exists already"
  exit 1
fi

mkdir "${TMPDIR}"

unzip -q -d "${TMPDIR}" "${ZIP}"
ZIP_DIR="$(cd "${TMPDIR}"; echo *)"

mv "${TMPDIR}"/* "${DIR}"

ABS_DIR="$(cd "${DIR}"; pwd)"

find "${DIR}" -type f -print0   \
|xargs -0 grep -l "${REPO_DIR}" \
|while read f; do
  sed -i "${f}" -e "s,${REPO_DIR},file://${ABS_DIR}/svn.repo,g"
done
